package com.stylefeng.guns.rest.common.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @ClassName FTPUtil
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/9/18  23:58
 * @Version 1.0
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "ftp")
public class FTPUtil {

    // 地址 端口 用户名 密码
    private String hostName ; //= "192.168.199.144"
    private Integer port ;//= 2100
    private String username ;//= "Administrator"
    private String password;// = "19940619"

    private FTPClient ftpClient = null;

    private void initFTPClient() {
        try {
            ftpClient = new FTPClient();
            ftpClient.setControlEncoding("utf-8");
            ftpClient.connect(hostName, port);
            //ftp 需要登录的
            ftpClient.login(username, password);


        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }


    //输入一个路径 将路径中的文件转换为字符串返回
    public String getFileStrByAddress(String path) {
        BufferedReader bufferedReader = null;
        try {
            //读流
            initFTPClient();
            //以下 写法关流的时候需要关两个
//            InputStream inputStream = ftpClient.retrieveFileStream(path);
//            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //这种写法 只需要关闭 bufferedReader
            bufferedReader = new BufferedReader(new InputStreamReader(ftpClient.retrieveFileStream(path)));
            StringBuffer sb = new StringBuffer();
            while (true) {
                String s = bufferedReader.readLine();
                if (s == null) {
                    break;
                }
                sb.append(s);
            }

            ftpClient.logout();
            return sb.toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static void main(String[] args) {
        FTPUtil ftpUtil = new FTPUtil();
        String fileStrByAddress = ftpUtil.getFileStrByAddress("seats/cgs.json");
        System.out.println(fileStrByAddress);

    }


}
